<?php
/*
 * Author  : Tran Quoc Bao
 * Created : 20-10-2011
 */
class config{
	     
    static function get($name = 'general'){ 
        $rs = Zend_Registry::get('config')->$name->toArray();
        return $rs;
    }
    static function set($file = 'config.ini',$node = 'info',$array){
        if($file == ''){
            $file = 'config.ini';
        }
        if($node == ''){
            $node = 'info';
        }
       
        $path = APPLICATION_PATH . '/configs/'.$file;
        if($file == 'config.ini'){
            self::setConfigFile($node,$array,$path);
        }
        if($file == 'auth.ini'){
            self::setAuthFile($node,$array,$path);
        }
        if($file == 'sourcesDescription.ini'){
            self::setDescriptionFile($node,$array,$path);
        }
    }    
    private function setConfigFile($node = 'info',$array,$path){
        $config = new Zend_Config_Ini($path,
                              null,
                              array('skipExtends'        => true,
                                    'allowModifications' => true));       
        foreach(array_keys($array) as $item)
        {
            $config->general->$node->$item = $array[$item];
        }
        $writer = new Zend_Config_Writer_Ini(array('config'   => $config,
                                                   'filename' => $path));
        $writer->write();
    }

    private function setAuthFile($moduleName = 'default',$array,$path){
        $config = new Zend_Config_Ini($path,
                                      null,
                                      array(
                                            'skipExtends'        => true,
                                            'allowModifications' => true
                                            )
                                        );
        $config->general->module->$moduleName = array();
        foreach(array_keys($array) as $item)
        {
            $config->general->module->$moduleName->$item = $array[$item];
        }
        
        $writer = new Zend_Config_Writer_Ini(array('config'   => $config,
                                                   'filename' => $path));
        $writer->write();
    }
    private function setDescriptionFile($moduleName = 'default',$resources,$path){
        $config = new Zend_Config_Ini($path,
                                      null,
                                      array(
                                            'skipExtends'        => true,
                                            'allowModifications' => true
                                            )
                                        );
        $i = 0;                                
        if(count($config->general) == 0){
        $i++;                                
            $moduleName = $resources[0]['MODULE'];
            $config->general = array();
            $config->general->module = array();
            $config->general->module->$moduleName = array();
            $config->general->module->$moduleName->description = $moduleName;
            $config->general->module->$moduleName->controller = array();
                foreach($resources[0]['CONTENT'] as $subItem){
                $controllerName = $subItem["CONTROLLER"];
                $config->general->module->$moduleName->controller->$controllerName = array();
                $config->general->module->$moduleName->controller->$controllerName->description = $subItem["DESCRIPTION"];
                $config->general->module->$moduleName->controller->$controllerName->action = array();
                    foreach($subItem["ACTIONS"] as $actionItem){
                        $actionName = $actionItem["NAME"];                        
                        $config->general->module->$moduleName->controller->$controllerName->action->$actionName = array();
                        $config->general->module->$moduleName->controller->$controllerName->action->$actionName->description = $actionItem["DESCRIPTION"];                        
                    }
                }
        
        $writer = new Zend_Config_Writer_Ini(array('config'   => $config,
                                                   'filename' => $path));
        $writer->write();
        }
        
        for($i;$i<count($resources); $i++){
            $moduleName = $resources[$i]["MODULE"];
            $config->general->module->$moduleName = array();
            $config->general->module->$moduleName->description = $moduleName;
            $config->general->module->$moduleName->controller = array();
            foreach($resources[$i]["CONTENT"] as $subItem){
                $controllerName = $subItem["CONTROLLER"];
                $config->general->module->$moduleName->controller->$controllerName = array();
                $config->general->module->$moduleName->controller->$controllerName->description= $subItem["DESCRIPTION"];
                $config->general->module->$moduleName->controller->$controllerName->action = array();
                foreach($subItem["ACTIONS"] as $actionItem){
                    $actionName = $actionItem["NAME"];
                    $config->general->module->$moduleName->controller->$controllerName->action->$actionName = $actionItem["DESCRIPTION"];                    
                }
            }
            $writer = new Zend_Config_Writer_Ini(array('config'   => $config,
                                                   'filename' => $path));
            $writer->write();
        }
        
    }
    static function getAuth(){
        $rs = Zend_Registry::get('auth_config')->module->toArray();
        return $rs;
    }
    static function getSourcesDescription(){
        $sD = new Zend_Config_Ini(CONFIG_PATH.'\sourcesDescription.ini','general');
        return $sD;
    }
    static function getGeneral($name = ''){
        $rs = Zend_Registry::get('config')->general->toArray();
        return self::returnConfig($rs,$name);
    }  
    static function getPage($name = ''){     
        $rs = Zend_Registry::get('config')->page->toArray();
        return self::returnConfig($rs,$name);
    }
    static function getOrg($name = ''){     
        $rs = Zend_Registry::get('config')->org->toArray();
        return self::returnConfig($rs,$name);
    }
    static function getContact($name = ''){     
        $rs = Zend_Registry::get('config')->contact->toArray();
        return self::returnConfig($rs,$name);
    }
    static function getEmail($name = ''){     
        $rs = Zend_Registry::get('config')->email->toArray();
        return self::returnConfig($rs,$name);
    }
    static function getSystemRoles(){
        $rs = Zend_Registry::get('auth_config')->system->roles;
        return $rs;
    }
    static function setSystemRoles($roles){
        $path = APPLICATION_PATH . '/configs/auth.ini';
        $config = new Zend_Config_Ini($path,
                                      null,
                                      array(
                                            'skipExtends'        => true,
                                            'allowModifications' => true
                                            )
                                        );
        $config->general->system->roles  = $roles;
        
        $writer = new Zend_Config_Writer_Ini(array('config'   => $config,
                                                   'filename' => $path));
        $writer->write();
    }
    static function addSystemRoles($role){
        $systemRoles = self::getSystemRoles();
        $systemRoles .= ','.$role;
        self::setSystemRoles($systemRoles);        
    }
    static function getModule($module = 'default'){     
        $rs = Zend_Registry::get('auth_config')->module->$module->toArray();
        return $rs;
    }
    
    static function replaceRoles($oldRole,$newRole){
        $array      = self::getAuth();
        $systemRole = self::getSystemRoles();

        $path = APPLICATION_PATH . '/configs/auth.ini';
        $config = new Zend_Config_Ini($path,
                                      null,
                                      array(
                                            'skipExtends'        => true,
                                            'allowModifications' => true
                                            )
                                        );
        // replace system.roles
        $config->general->system->roles  = str_replace($oldRole,$newRole,$systemRole);
        while ($fruit_name = current($array)) {
            $module = key($array);
            $oldAllow = $array[$module]['allow'];
            $newAllow = str_replace($oldRole,$newRole,$oldAllow);
            $config->general->module->$module->allow = $newAllow;
            next($array);
        }
        $writer = new Zend_Config_Writer_Ini(array('config'   => $config,
                                                   'filename' => $path));
        $writer->write();
    }

    static function removeRoles($roleToRemove){
        $array      = self::getAuth();
        $systemRole = self::getSystemRoles();
        $arrSystemRole = explode(",",$systemRole);
        $keys = array_keys($arrSystemRole, $roleToRemove);
        unset($arrSystemRole[$keys[0]]);
        $newStr = implode(",",$arrSystemRole);
        self::setSystemRoles($newStr);

        $path = APPLICATION_PATH . '/configs/auth.ini';
        $config = new Zend_Config_Ini($path,
                                      null,
                                      array(
                                            'skipExtends'        => true,
                                            'allowModifications' => true
                                            )
                                        );
        while ($fruit_name = current($array)) {
            $module = key($array);
            $oldAllow = $array[$module]['allow'];
            
            $arrRoles = explode(",",$oldAllow);
            $keys = array_keys($arrRoles, $roleToRemove);
            unset($arrRoles[$keys[0]]);
            $newStrRoles = implode(",",$arrRoles);
            
            $config->general->module->$module->allow = $newStrRoles;
            next($array);
        }
        $writer = new Zend_Config_Writer_Ini(array('config'   => $config,
                                                   'filename' => $path));
        $writer->write();
    }

    private function returnConfig($rs,$name){
        if($name != '')
        {
        return $rs[$name];
        }
        return $rs;
    }
    
    static function updatePermission($role,$module,$data){
        $dataCurrentConfig = self::getModule($module);
        $arrAllow = explode(",",$dataCurrentConfig['allow']);
        $arrDeny = explode(",",$dataCurrentConfig['deny']);
        //var_dump($dataCurrentConfig['name']);exit;
        $arrDenyAfterFilter = array();
        $arrAllowAfterFilter = array();
        $arrDenyNew = array();
        $arrAllowNew = array();
        
        // filter Denny Array
        foreach($arrDeny as $itemDeny){
            $roleDeny = explode(":",$itemDeny);
            if($roleDeny[0] != $role && $itemDeny != ""){
                $arrDenyAfterFilter[] = $itemDeny;
                $arrDenyNew[] = $itemDeny;
            }
        }
        // filter Allow Array
        foreach($arrAllow as $itemAllow){
            if($itemAllow != $role && $itemAllow != ''){
                $arrAllowAfterFilter[] = $itemAllow;
                $arrAllowNew[] = $itemAllow;
            }
        } 
        
        $isAllow = 0;
        foreach($data as $item){
            if($item['VALUE'] == '1'){
                $isAllow = 1;
            }else{
                $arrDenyAfterFilter[] = $role.':'.strtolower($item['NAME']);
            }
        }
        $strDeny = "";
        $strAllow = "";
        if($isAllow == 1){
            $arrAllowAfterFilter[] = $role;
            $strDeny = implode(",",$arrDenyAfterFilter);
        }else{
            $strDeny = implode(",",$arrDenyNew);
        }
        $strAllow = implode(",",$arrAllowAfterFilter);
        
        $data = array (
            'name' => $dataCurrentConfig['name'],
            'controllers' => $dataCurrentConfig['controllers'],
            'allow' => $strAllow,
            'gotourlandexit' => $dataCurrentConfig['gotourlandexit'],
            'isauth' => $dataCurrentConfig['isauth'],
            'deny' => $strDeny
        );
        
        self::set('auth.ini',$module,$data);
    }
}